$(function () {
    //加载弹出层
    layui.use(['form', 'element'],
        function () {
            layer = layui.layer;
            element = layui.element;
        });

    //触发事件
    var tab = {
        tabAdd: function (title, url, id) {
            //新增一个Tab项
            element.tabAdd('xbs_tab', {
                title: title
                ,
                content: '<iframe tab-id="' + id + '" frameborder="0" src="' + url + '" scrolling="yes" class="x-iframe"></iframe>'
                ,
                id: id
            })
        }
        , tabDelete: function (othis) {
            //删除指定Tab项
            element.tabDelete('xbs_tab', '44'); //删除：“商品管理”


            othis.addClass('layui-btn-disabled');
        }
        , tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('xbs_tab', id); //切换到：用户管理
        }
    };


    tableCheck = {
        init: function () {
            $(".layui-form-checkbox").click(function (event) {
                if ($(this).hasClass('layui-form-checked')) {
                    $(this).removeClass('layui-form-checked');
                    if ($(this).hasClass('header')) {
                        $(".layui-form-checkbox").removeClass('layui-form-checked');
                    }
                } else {
                    $(this).addClass('layui-form-checked');
                    if ($(this).hasClass('header')) {
                        $(".layui-form-checkbox").addClass('layui-form-checked');
                    }
                }

            });
        },
        getData: function () {
            var obj = $(".layui-form-checked").not('.header');
            var arr = [];
            obj.each(function (index, el) {
                arr.push(obj.eq(index).attr('data-id'));
            });
            return arr;
        }
    }

    //开启表格多选
    tableCheck.init();


    $('.container .left_open i').click(function (event) {
        if ($('.left-nav').css('left') == '0px') {
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        } else {
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if ($(window).width() < 768) {
                $('.page-content-bg').show();
            }
        }

    });

    $('.page-content-bg').click(function (event) {
        $('.left-nav').animate({left: '-221px'}, 100);
        $('.page-content').animate({left: '0px'}, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function (event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    if ($("tbody.x-cate tr[fid='0']").length > 0) {
        $("tbody.x-cate tr[fid!='0']").hide();
    }

    // 栏目多级显示效果
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {
            cateIds = [];
            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            getCateId(cateId);
            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })

    //左侧菜单效果
    // $('#content').bind("click",function(event){
    $('.left-nav #nav li').click(function (event) {

        if ($(this).children('.sub-menu').length) {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $(this).find('.nav_right').html('&#xe697;');
                $(this).children('.sub-menu').stop().slideUp();
                $(this).siblings().children('.sub-menu').slideUp();
            } else {
                $(this).addClass('open');
                $(this).children('a').find('.nav_right').html('&#xe6a6;');
                $(this).children('.sub-menu').stop().slideDown();
                $(this).siblings().children('.sub-menu').stop().slideUp();
                $(this).siblings().find('.nav_right').html('&#xe697;');
                $(this).siblings().removeClass('open');
            }
        } else {

            var url = $(this).children('a').attr('_href');
            var title = $(this).find('cite').html();
            var index = $('.left-nav #nav li').index($(this));

            for (var i = 0; i < $('.x-iframe').length; i++) {
                if ($('.x-iframe').eq(i).attr('tab-id') == index + 1) {
                    tab.tabChange(index + 1);
                    event.stopPropagation();
                    return;
                }
            }
            ;

            tab.tabAdd(title, url, index + 1);
            tab.tabChange(index + 1);
        }

        event.stopPropagation();

    })

})
var cateIds = [];

function getCateId(cateId) {

    $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
        id = $(el).attr('cate-id');
        cateIds.push(id);
        getCateId(id);
    });
}

/*弹出层*/

/*
    参数解释：
    title   标题
    url     请求的url
    id      需要操作的数据id
    w       弹出层宽度（缺省调默认值）
    h       弹出层高度（缺省调默认值）
*/
function x_admin_show(title, url, w, h) {
    if (title == null || title == '') {
        title = false;
    }
    ;
    if (url == null || url == '') {
        url = "404";
    }
    ;
    if (w == null || w == '') {
        w = ($(window).width() * 0.9);
    }
    ;
    if (h == null || h == '') {
        h = ($(window).height() - 50);
    }
    ;
    layer.open({
        type: 2,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade: 0.4,
        title: title,
        content: url
    });
}

/*关闭弹出框口*/
function x_admin_close() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

/**
 * 以下内容 后期添加
 * ---------------------------------------------------------------------------------------
 * @author Christopher Jones
 */

/**
 * 后台专用图片上传
 * @param btnId 上传组件的ID
 * @param param 图片上传目录名
 * @param callback 上传成功后的回调函数，函数接收两个参数（哪个控件,上传图片的URL）
 * @param pressText 是否上水印 false或空 否 true是
 * @param cutImg 是拉伸图片 false或空 否 true是
 * @param width height 图片拉伸后宽高
 */
function initSimpleImageUpload(btnId, param, callback, pressText, cutImg, width, height) {
    if (KindEditor) {
        KindEditor.create();
        var uploadbutton = KindEditor.uploadbutton({
            button: KindEditor('#' + btnId + '')[0],
            fieldName: "uploadfile",
            url: uploadServer + "/image/gok4?" + '&param=' + param + '&pressText=' + pressText + '&cutImg=' + cutImg +
            '&width=' + width + '&height=' + height,
            afterUpload: function (data) {
                if (data.error == 0) {
                    var url = KindEditor.formatUrl(data.url, 'absolute');//absolute,domain
                    callback(btnId, url);
                } else {
                    layer.msg(data.message, {icon: 5});
                }
            },
            afterError: function (str) {
                layer.msg('上传失败！', {icon: 5});
                console.log(str);
            }
        });
        uploadbutton.fileBox.change(function (e) {
            uploadbutton.submit();
        });
    }
    $('body .ke-upload-file').attr('accept', "image/jpeg, image/png, image/jpg");
}

/**
 * 上传头像回调
 * @param btnId
 * @param url
 */
function calTitleImg(btnId, url, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio) {
    // 销毁图片插件
    $(jcropDesctroy).click();
    $(imgWrapper).attr("style", "");
    $(imgWrapper).attr("src", fileServer + url);
    $(jcropPreview).attr("src", fileServer + url);
    $(valueInput).val(url);

    var img = new Image();
    img.src = fileServer + url;
    img.onload = function () {
        var tagName = $(valueInput).prop('name');
        var realHeight = img.height;
        var realWidth = img.width;
        if (realHeight >= realWidth && realHeight > 300) {
            var height = 300;
            var width = height * realWidth / realHeight;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(Math.ceil(width));
            $('#' + tagName + '_height').val(height);
        } else if (realHeight < realWidth && realWidth > 300) {
            var width = 300;
            var height = width * realHeight / realWidth;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(width);
            $('#' + tagName + '_height').val(Math.ceil(height));
        } else {
            var height = realHeight;
            var width = realWidth;
            $(imgWrapper).attr("height", height);
            $(imgWrapper).attr("width", width);
            $('#' + tagName + '_width').val(Math.ceil(width));
            $('#' + tagName + '_height').val(height);
        }
        editingPhotos(valueInput, imgWrapper, previewPane, jcropDesctroy, ratio);
    };
}

/**
 * 编辑图片
 */
function editingPhotos(valueInput, imgWrapper, previewPane, jcropDesctroy, ratio) {
    jQuery(function ($) {
        var jcrop_api,
            boundx,
            boundy,
            $preview = $('.preview-pane'),
            $pcnt = $(previewPane + ' .preview-container'),
            $pimg = $(previewPane + ' .preview-container img'),
            xsize = $pcnt.width(),
            ysize = $pcnt.height();

        $(imgWrapper).Jcrop({
            onChange: updatePreview,
            onSelect: updatePreview,
            allowSelect: false,//是否允许新选框
            minSize: [50, 50],//选框最小尺寸
            aspectRatio: ratio
        }, function () {
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            jcrop_api.animateTo([80, 50, 80, 20]);
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c) {
            var tagName = $(valueInput).prop('name');
            $('#' + tagName + '_left').val(c.x);
            $('#' + tagName + '_top').val(c.y < 0 ? 0 : c.y);
            $('#' + tagName + '_DropWidth').val(Math.round(c.w) - 1);
            $('#' + tagName + '_DropHeight').val(Math.round(c.h) - 1);
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        }

        $(jcropDesctroy).click(function (e) {
            jcrop_api.destroy();
            return false;
        });
    });
}

/**
 * 前台专用图片上传
 * @param btnId 上传组件的ID
 * @param param 图片上传目录名
 * @param callback 上传成功后的回调函数，函数接收一个参数（上传图片的URL）
 */
function webImageUpload(btnId, param, callback, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio) {
    var uploadbutton = KindEditor.uploadbutton({
        button: KindEditor('#' + btnId + '')[0],
        fieldName: "uploadfile",
        url: uploadServer + '/image/gok4?&param=' + param + '&fileType=jpg,gif,png,jpeg',
        afterUpload: function (data) {
            console.log(data)
            if (data.error == 0) {
                var url = KindEditor.formatUrl(data.url, 'absolute');//absolute,domain
                $('#' + btnId).addClass('')
                callback(btnId, url, valueInput, imgWrapper, previewPane, jcropPreview, jcropDesctroy, ratio);
            } else {
                layer.alert(data.message, {icon: 1, time: 3000})
            }
        },
        afterError: function (str) {
            console.error(str);
            layer.alert('自定义错误信息: ' + str, {icon: 1, time: 3000})
        }
    });
    uploadbutton.fileBox.change(function (e) {
        uploadbutton.submit();
    });
}

/**
 * 删除
 * @param argument
 */
function del(url, id, msg) {
    if (id == undefined || id == null) {
        id = tableCheck.getData();
    }
    if (id == undefined || id == null || id.length == 0) {
        layer.msg('请选择要删除的数据', {icon: 1, time: 3000});
        return false;
    }
    layer.confirm((msg != null && msg != '') ? msg : Messages.CONFIRM_DELETE, function (index) {
        $.ajax({
            type: 'delete',
            url: url + id,
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader($("meta[name='_csrf_header']").attr("content"), $("meta[name='_csrf']").attr("content"));
            },
            success: function (result) {
                if (result.status == 200) {
                    layer.msg(result.data, {icon: 6, time: 3000});
                    setTimeout(function () {
                        location.reload();
                    }, 2000)
                } else {
                    layer.msg(result.error == null || result.error == undefined ? Messages.DELETE_FAILED : result.error, {
                        icon: 1,
                        time: 3000
                    });
                }
            },
            error: function (e) {
                layer.msg(Messages.ERROR, {icon: 1, time: 3000});
            }
        })
    });
}

/**
 * 公共信息
 * @type {{ERROR: string, SUCCESS: string}}
 */
var Messages = {
    HTTP_STATUS: {
        SUCCESS: 200
    },
    TOF: {
        TRUE: true,
        FALSE: false
    },

    ERROR: '操作失败, 请稍候再试',
    SUCCESS: '操作成功',
    DELETE_SUCCESS: '删除成功',
    DELETE_FAILED: '删除失败',
    CONFIRM_DELETE: '确认删除?',

    USER: {
        ROLES_CAN_NOT_BE_NULL: '请选择用户权限',
    },

    TIP: {
        msg: function(msg) {
            layer.msg(msg, {icon: 6, time: 3000});
        },
        error: function(msg, defaul) {
            var err = defaul ? defaul : this.ERROR;
            layer.alert(msg == null || msg == undefined ? err : msg, {icon: 1});
        }
    }
}